<template>
  <ele-page>
    <!-- 搜索表单 -->
    <search @search="reload" :badge-data="badgeData" />
    <ele-card :body-style="{ paddingTop: '8px' }">
      <!-- 表格 -->
      <ele-pro-table
        ref="tableRef"
        :columns="columns"
        :datasource="datasource"
        :show-overflow-tooltip="true"
        highlight-current-row
        stripe
        border
        :max-height="browserHeight - 200 + 'px'"
        :where="defaultWhere"
      >
        <template #toolbar>
          <el-button type="success" @click="openCreate" :icon="Plus">
            新建出单表
          </el-button>
        </template>
        <template #vehicle="{ row }">
          {{ row.area }}
          <br />
          {{ row.company }}
          <br />
          {{ row.plate_number }}
          <br v-if="status == 4 || status == 3" />
          <span class="red" v-if="status == 4 || status == 3">{{
            row.back_reason
          }}</span>
        </template>
        <template #insurance_qx="{ row }">
          <span :class="priceClass(row.qx_price)" @click="openInsurance(row)">{{
            priceText(row.qx_price)
          }}</span>
          <!-- <br />
          <span v-if="status == 0">报价单({{ row.qx_offer }})</span> -->
        </template>
        <template #insurance_sy="{ row }">
          <span
            :class="priceClass(row.syx_price)"
            @click="openInsurance(row)"
            >{{ priceText(row.syx_price) }}</span
          >
          <!-- <br />
          <span v-if="status == 0">报价单({{ row.syx_offer }})</span> -->
        </template>
        <template #insurance_qt="{ row }">
          <span :class="priceClass(row.qtx_price)" @click="openInsurance(row)">
            {{ priceText(row.qtx_price) }}
          </span>
          <!-- <br />
          <span v-if="status == 0">报价单({{ row.cpx_offer }})</span> -->
        </template>

        <template #profit_target="{ row }">
          {{ row.profit_target }}
          <br />
          <span v-if="row.custom_profit_flag == 1">
            {{ row.custom_profit_target }}
          </span>
        </template>

        <template #profit="{ row }">
          <span :class="profitClass(row)">{{ row.profit }}</span>
        </template>

        <template #price="{ row }">
          <span class="pointer blue" @click="openPrice(row)">{{
            row.price
          }}</span>
        </template>
        <template #paid="{ row }">
          <span class="pointer blue" @click="openPay(row)">{{ row.paid }}</span>
        </template>
        <template #diff="{ row }">
          {{ row.diff_price }} <br />
          {{ row.diff_price_type }}
        </template>

        <template #dianfu="{ row }">
          {{ row.dianfu_amount }}<br />
          <el-link type="success" :underline="false" @click="openDianfu(row)">
            {{ status == 0 ? '信息录入' : '查看详情' }}
          </el-link>
        </template>
        <template #fenqi="{ row }">
          <span class="orange" v-if="row.fenqi_first_pay != '0.00'">
            首付：{{ row.fenqi_first_pay }}<br />
          </span>
          {{ row.fenqi_amount }}<br />
          <el-link
            type="success"
            :underline="false"
            @click="openInstallment(row)"
          >
            {{ status == 0 ? '信息录入' : '查看详情' }}
          </el-link>
        </template>
        <template #pay-img="{ row }">
          <span
            v-if="row.pay_images !== ''"
            class="pointer blue"
            @click="openImages(row.payImages)"
            >查看</span
          >
          <span v-else>无</span>
        </template>
        <template #watingPay="{ row }">
          <span class="pointer blue" @click="openWatingPay(row)">查看</span>
        </template>
        <template #check="{ row }">
          <span class="pointer blue" @click="openCheck(row)">复核金额</span>
        </template>
        <template #toJudgeDateTime="{ row }">
          {{ row.to_judge_user }}<br />
          {{ row.toJudgeDate }}<br />
          {{ row.toJudgeTime }}
        </template>
        <template #backTime="{ row }">
          {{ row.back_user }}<br />
          {{ row.toJudgeDate }}<br />
          {{ row.toJudgeTime }}
        </template>
        <template #judgeTime="{ row }">
          {{ row.judge_user }}<br />
          {{ row.judgeDate }}<br />
          {{ row.judgeTime }}
        </template>
        <template #remark="{ row }">
          {{ row.remark }}<br />
          <el-link
            v-if="status == 0 || status == 4"
            type="primary"
            :underline="false"
            @click="openRemark(row, 'edit')"
          >
            {{ row.remark ? '编辑' : '添加' }}
          </el-link>
          <el-link
            v-else
            type="primary"
            :underline="false"
            @click="openRemark(row, 'view')"
          >
            查看更多
          </el-link>
        </template>
        <template #action="{ row }">
          <el-dropdown @command="handleCommand" :show-timeout="0">
            <el-button type="primary" size="small">
              操作
              <el-icon class="el-icon--right">
                <arrow-down />
              </el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item
                  v-if="row.status < 5"
                  :command="beforeHandleCommand(row, '提交到审核')"
                >
                  提交
                </el-dropdown-item>
                <el-dropdown-item
                  v-if="row.status == 5"
                  :command="beforeHandleCommand(row, '提交到出单')"
                >
                  提交
                </el-dropdown-item>
                <el-dropdown-item
                  v-if="row.status == 5 || row.status == 10 || row.status == 20"
                  :command="beforeHandleCommand(row, '退回')"
                >
                  退回
                </el-dropdown-item>
                <el-dropdown-item
                  v-if="row.status < 5"
                  :command="beforeHandleCommand(row, '删除')"
                >
                  删除
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </ele-pro-table>
    </ele-card>
    <!-- 图片 -->
    <images v-model="showImages" :data="current" />
    <!-- 保单列表 -->
    <offer-list v-model="showOffer" :data="current" @done="chooseDone" />
    <!-- 新建 -->
    <create v-model="showCreate" @done="reload" />
    <!-- 编辑付款信息 -->
    <pay v-model="showPay" :data="current" @done="reload" />
    <!-- 编辑价格信息 -->
    <price v-model="showPrice" :data="current" @done="reload" />
    <!-- 分期 -->
    <installment v-model="showInstallment" :data="current" @done="reload" />
    <!-- 垫付 -->
    <dianfu v-model="showDianfu" :data="current" @done="reload" />
    <!-- 备注 -->
    <remark
      v-model="showRemark"
      :show-type="showRemarkType"
      :data="current"
      @done="reload"
    />
    <!-- 退回 -->
    <back v-model="showBack" :data="current" @done="reload" />
    <!-- 待付款列表 -->
    <WatingPay v-model="showWatingPay" :data="current" @done="reload" />
  </ele-page>
</template>

<script setup>
  import { ref, computed, onBeforeUnmount, onMounted } from 'vue';
  import {
    pageTradeList,
    tradeToBuy,
    tradeToJudge,
    delTrade
  } from '@/api/company';
  import Images from './components/images.vue';
  import Search from './components/search.vue';
  import Installment from './components/installment.vue';
  import Dianfu from './components/dianfu.vue';
  import Remark from './components/remark.vue';
  import Create from './components/create.vue';
  import Back from './components/back.vue';
  import Pay from './components/pay.vue';
  import WatingPay from './components/wating-pay.vue';
  import Price from './components/price.vue';
  import OfferList from './components/offer-list.vue';
  import { ElMessageBox } from 'element-plus/es';
  import { ElMessage } from 'element-plus';
  import { Plus, ArrowDown } from '@element-plus/icons-vue';

  /** 价格显示 */
  const priceText = (value) => {
    if (status.value == 200) {
      if (value == 0) return '无';
    }
    return value;
  };

  /** 利润颜色 */
  const profitClass = (row) => {
    var target =
      row.custom_profit_target > 0
        ? row.custom_profit_target * 100
        : row.profit_target * 100;
    var profit = row.profit * 100;
    return target > profit ? 'red' : 'green';
  };

  /** 价格显示的样式 */
  const priceClass = (value) => {
    if (status.value == 200) {
      return value == 0 ? '' : 'pointer blue';
    }
    return 'pointer blue';
  };

  const tableRef = ref(null);

  // 使用 ref 来保存浏览器高度
  const browserHeight = ref(
    window.innerHeight ||
      document.documentElement.clientHeight ||
      document.body.clientHeight
  );

  // 更新浏览器高度
  const updateHeight = () => {
    browserHeight.value =
      window.innerHeight ||
      document.documentElement.clientHeight ||
      document.body.clientHeight;
  };

  onMounted(() => {
    // 组件挂载后初始化并监听窗口大小变化
    window.addEventListener('resize', updateHeight);
  });

  onBeforeUnmount(() => {
    // 组件销毁前移除监听事件
    window.removeEventListener('resize', updateHeight);
  });

  /** 表格列配置 */
  const columns = computed(() => {
    const cols = [];

    cols.push(
      {
        width: 70,
        prop: 'id',
        label: '编号',
        align: 'center',
        fixed: 'left'
      },
      {
        minWidth: 200,
        slot: 'vehicle',
        label: '车辆信息',
        align: 'center',
        fixed: 'left'
      }
    );
    cols.push(
      {
        label: '利润',
        align: 'center',
        children: [
          {
            slot: 'profit_target',
            label: '指标/自定',
            width: 100,
            align: 'center'
          },
          {
            slot: 'profit',
            label: '当前利润',
            width: 100,
            align: 'center'
          }
        ]
      },
      {
        label: '付款信息',
        align: 'center',
        children: [
          {
            slot: 'price',
            label: '应收',
            width: 100,
            align: 'center'
          },
          {
            slot: 'paid',
            label: '实收',
            width: 100,
            align: 'center'
          },
          {
            width: 120,
            slot: 'dianfu',
            label: '垫付',
            align: 'center'
          },
          {
            width: 120,
            slot: 'fenqi',
            label: '分期',
            align: 'center'
          },
          {
            slot: 'diff',
            label: '差价',
            width: 100,
            align: 'center'
          },
          {
            width: 120,
            slot: 'pay-img',
            label: '司机付款图片',
            align: 'center'
          }
        ]
      },

      {
        slot: 'remark',
        label: '备注',
        width: 100,
        align: 'center'
      },
      {
        label: '保险',
        align: 'center',
        children: [
          {
            width: 100,
            prop: 'tax_price',
            label: '车船税',
            align: 'center'
          },
          {
            width: 100,
            slot: 'insurance_qx',
            label: '交强险',
            align: 'center'
          },
          {
            width: 100,
            slot: 'insurance_sy',
            label: '商业险',
            align: 'center'
          },
          {
            width: 100,
            slot: 'insurance_qt',
            label: '其他险种',
            align: 'center'
          }
        ]
      },

      {
        prop: 'fenqi_charge_amount',
        label: '分期手续费',
        width: 100,
        align: 'center'
      },

      {
        prop: 'glf_price',
        label: '管理费',
        width: 100,
        align: 'center'
      },
      {
        prop: 'gps_price',
        label: 'GPS费',
        width: 100,
        align: 'center'
      },
      {
        prop: 'eb_price',
        label: '二保费',
        width: 100,
        align: 'center'
      },
      {
        prop: 'xx_price',
        label: '学习费',
        width: 100,
        align: 'center'
      },
      {
        prop: 'gz_price',
        label: '盖章费',
        width: 100,
        align: 'center'
      },
      {
        prop: 'fw_price',
        label: '法务费',
        width: 100,
        align: 'center'
      },
      {
        prop: 'qt_price',
        label: '其他费用',
        width: 100,
        align: 'center'
      }
    );
    if (status.value == 3 || status.value == 4) {
      cols.push({
        slot: 'backTime',
        label: '退回人',
        width: 100,
        align: 'center',
        fixed: 'right'
      });
    }
    if (status.value == 10) {
      cols.push({
        slot: 'judgeTime',
        label: '发送人',
        width: 100,
        align: 'center',
        fixed: 'right'
      });
    }
    if (status.value == 5) {
      cols.push({
        slot: 'toJudgeDateTime',
        label: '提交时间',
        width: 100,
        align: 'center',
        fixed: 'right'
      });
    }
    if (status.value == 20) {
      cols.push({
        slot: 'watingPay',
        label: '待付款',
        width: 100,
        align: 'center',
        fixed: 'right'
      });
    }
    if (status.value == 190) {
      cols.push({
        slot: 'check',
        label: '复核',
        width: 100,
        align: 'center',
        fixed: 'right'
      });
    }

    if (
      status.value == 0 ||
      status.value == 3 ||
      status.value == 4 ||
      status.value == 5 ||
      status.value == 10 ||
      status.value == 20 ||
      status.value == 30
    ) {
      cols.push({
        slot: 'action',
        label: '操作',
        width: 100,
        align: 'center',
        fixed: 'right'
      });
    }

    if (status.value == 200) {
      cols.push({
        prop: 'doneTime',
        label: '出单日期',
        width: 100,
        align: 'center',
        fixed: 'right'
      });
    }

    return cols;
  });

  /** 表格数据源 */
  const defaultWhere = ref({
    status: 0,
    area_id: '',
    company: '',
    plate_number: '',
    fenqi: 99999999,
    dianfu: 99999999
  });
  const datasource = async ({ page, limit, where, orders }) => {
    const result = await pageTradeList({
      ...where,
      ...orders,
      page,
      limit
    });
    badgeData.value = result.badgeData;

    return result;
  };
  const badgeData = ref([]);
  /** 搜索 */
  const reload = (where) => {
    tableRef.value?.reload?.({ page: 1, where });
    status.value = where ? where.status : 0;
  };

  const current = ref([]);

  /** 查看图片 */
  const showImages = ref(false);
  const openImages = (data) => {
    current.value = data;
    showImages.value = true;
  };

  /** 查看出单要求 */
  const showOffer = ref(false);
  const openInsurance = (row) => {
    current.value = row;
    showOffer.value = true;
  };

  /** 查看出单要求 */
  const showBack = ref(false);
  const openBack = (row) => {
    current.value = row;
    showBack.value = true;
  };

  // /** 打开保单 */
  // const openPdf = () => {
  //   getTradeInsurancePdf({ trade_id: current.value.id, cate: showCate.value })
  //     .then((res) => {
  //       loading.value = false;
  //       window.open(res);
  //     })
  //     .catch((e) => {
  //       loading.value = false;
  //       console.log(e);
  //     });
  // };

  /** 新建出单表 */
  const showCreate = ref(false);
  const openCreate = () => {
    showCreate.value = true;
  };

  /** 打开备注 */
  const showRemark = ref(false);
  const showRemarkType = ref('');
  const openRemark = (row, type) => {
    current.value = row;
    showRemarkType.value = type;
    showRemark.value = true;
  };

  /** 付款信息 */
  const showPay = ref(false);
  const openPay = (row) => {
    current.value = row;
    showPay.value = true;
  };

  /** 应付信息信息 */
  const showPrice = ref(false);
  const openPrice = (row) => {
    current.value = row;
    showPrice.value = true;
  };

  /** 分期信息 */
  const showInstallment = ref(false);

  const openInstallment = (row) => {
    current.value = row;
    showInstallment.value = true;
  };

  /** 分期信息 */
  const showDianfu = ref(false);
  const openDianfu = (row) => {
    current.value = row;
    showDianfu.value = true;
  };

  /** 付款列表 */
  const showWatingPay = ref(false);
  const openWatingPay = (row) => {
    current.value = row;
    showWatingPay.value = true;
  };

  /** 复核 */
  const openCheck = (row) => {
    current.value = row;
    showPay.value = true;
  };

  /** 选择完保险 */
  const chooseDone = () => {
    showOffer.value = false;
    reload();
  };

  /** 提交 */

  const checkDiffType = (row) => {
    const diff_price = row.diff_price;
    var res = true;
    if (diff_price == 0) return true;
    if (diff_price > 0) {
      if (row.diff_price_type != '利润' && row.diff_price_type != '返还')
        return false;
    }
    if (diff_price < 0) {
      if (row.diff_price_type != '欠款' && row.diff_price_type != '优惠')
        return false;
    }
    return res;
  };

  /** 提交出单通知 */
  const toJudge = (row = null) => {
    if (!checkDiffType(row)) {
      ElMessage.warning('此单有差价，请完善差价处理方式');
      return;
    }
    ElMessageBox.confirm(
      '确定将“' + row.plate_number + '”的出单通知提交到财务审核吗?',
      '系统提示',
      { type: 'warning', draggable: true }
    )
      .then(() => {
        tradeToJudge({ id: row.id })
          .then(() => {
            ElMessage.success('操作成功');
            reload();
          })
          .catch((e) => {
            console.log(e);
          });
      })
      .catch(() => {});
  };

  /** 提交出单通知 */
  const toBuy = (row = null) => {
    ElMessageBox.confirm(
      '确定将“' + row.plate_number + '”的出单通知提交到保险部吗?',
      '系统提示',
      { type: 'warning', draggable: true }
    )
      .then(() => {
        tradeToBuy({ id: row.id })
          .then(() => {
            ElMessage.success('操作成功');
            reload();
          })
          .catch((e) => {
            console.log(e);
          });
      })
      .catch(() => {});
  };

  /** 删除 */
  const del = (row = null) => {
    ElMessageBox.confirm(
      '确定将“编号' + row.id + '车牌号为' + row.plate_number + '”的出单删除吗?',
      '系统提示',
      { type: 'warning', draggable: true }
    )
      .then(() => {
        delTrade({ id: row.id })
          .then(() => {
            ElMessage.success('操作成功');
            reload();
          })
          .catch((e) => {
            console.log(e);
          });
      })
      .catch(() => {});
  };

  /** 操作 */
  const beforeHandleCommand = (row, command) => {
    return {
      row,
      command
    };
  };
  const handleCommand = (param) => {
    let action = param.command;
    let row = param.row;
    switch (action) {
      case '提交到审核':
        toJudge(row);
        break;
      case '提交到出单':
        toBuy(row);
        break;
      case '退回':
        openBack(row);
        break;
      case '删除':
        del(row);
        break;

      default:
        break;
    }
  };

  /** 当前列表参数 */
  const status = ref(0);
</script>
